//
//  PDFiumDocument.m
//  IAPDFKit
//
//  Created by macbook pro 2022 m2 on 2025/11/5.
//

#import "PDFiumDocument.h"
#import "PDFiumFileWrite.h"
#import "fpdf_doc.h"
#import "fpdf_save.h"
#import "fpdfview.h"
#import "fpdf_edit.h"
#import "fpdf_ppo.h"

@import CoreGraphics;
@import ImageIO;

@implementation PDFiumDocument

+ (void)initialize {
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        FPDF_LIBRARY_CONFIG config;
        config.version = 2;
        config.m_pUserFontPaths = NULL;
        config.m_pIsolate = NULL;
        config.m_v8EmbedderSlot = 0;
        FPDF_InitLibraryWithConfig(&config);
    });
}

- (instancetype _Nullable) initWithURL:(NSURL * _Nonnull)url password:(NSString* _Nullable) password {
    FPDF_STRING cpath = (char*) url.path.UTF8String;
    FPDF_STRING cpassword = (char*) password.UTF8String;
    _pdfiumDocumentRef = FPDF_LoadDocument(cpath, cpassword);
    if (_pdfiumDocumentRef == nil) {
        return nil;
    }
    _pageCount = FPDF_GetPageCount(_pdfiumDocumentRef);
    return self;
}

// 创建空文档
- (instancetype) init {
    self = [super init];
    if (self) {
        _pdfiumDocumentRef = FPDF_CreateNewDocument();
        if (_pdfiumDocumentRef == nil) {
            return nil;
        }
        _pageCount = 0;
    }
    return self;
}

// 从另一个文档导入页面
- (BOOL) importPagesFromDocument:(PDFiumDocument* _Nonnull)sourceDocument
                      pageIndices:(NSArray<NSNumber*>* _Nonnull)pageIndices
                        insertAt:(int)insertIndex {
    if (!sourceDocument.pdfiumDocumentRef || !_pdfiumDocumentRef) {
        return NO;
    }
    
    // 将NSArray转换为C数组
    int* indices = malloc(pageIndices.count * sizeof(int));
    for (int i = 0; i < pageIndices.count; i++) {
        indices[i] = [pageIndices[i] intValue];
    }
    
    // 只使用FPDF_ImportPagesByIndex导入指定页面
    BOOL success = FPDF_ImportPagesByIndex(_pdfiumDocumentRef,
                                          sourceDocument.pdfiumDocumentRef,
                                          indices,
                                          (unsigned long)pageIndices.count,
                                          insertIndex) != 0;
    
    if (success) {
        _pageCount = FPDF_GetPageCount(_pdfiumDocumentRef);
    }
    
    free(indices);
    return success;
}

// 保存文档到文件
- (BOOL) saveToURL:(NSURL* _Nonnull)url {
    if (!_pdfiumDocumentRef) {
        return NO;
    }
    
    FILE* file = fopen(url.path.UTF8String, "wb");
    if (!file) {
        return NO;
    }
    
    // 设置自定义文件写入结构
    CustomFileWrite customWrite;
    customWrite.base.version = 1;
    customWrite.base.WriteBlock = FileWriteCallback;
    customWrite.file = file;
    
    // 保存PDF
    BOOL success = FPDF_SaveAsCopy(_pdfiumDocumentRef, &customWrite.base, FPDF_NO_INCREMENTAL) != 0;
    
    fclose(file);
    return success;
}

- (void)dealloc {
    if (_pdfiumDocumentRef) {
        FPDF_CloseDocument(_pdfiumDocumentRef);
    }
}

@end
